<?php 
namespace Common\Service;   
use Common\Model\ErrorLogModel; 
use Common\Model\WeixinMemberModel;
use Common\Model\WeixinTemplateModel;
/**
 * 微信模板工具
 * @author liuyang
 * @version 2.0
 * @since 20160417
 */
class WeixinTemplateService {

    
    public static function send($templateId,$userId,$templateData,$url){ 
        $data = array(); 
        $weixinTemplateObj = (new WeixinTemplateModel())->getById($templateId); 
        if($weixinTemplateObj['id']>0){ 
            $fieldlist = json_decode($weixinTemplateObj['description'],true);  
            foreach($fieldlist as $key=>$val){
                $tempval = $templateData[$key]; 
                if(isset($tempval)){ 
                    $vallist = explode(",", $tempval);
                    $replaceList = array();
                    $count = 1;
                    foreach($vallist as $temp){
                        $replaceList['{'.$count.'}']=$temp;
                        $count++;
                    }  
                    $data[$key] = strtr($val['value'], $replaceList);
                }else{
                    $data[$key] =$val['value'];
                }
            } 
            if($url == null){
                $url = $weixinTemplateObj['url'];
            }  
           $rst = WeixinService::replyTemplate($userId, $weixinTemplateObj['weixin_template_id'],$data,$url);
            if($rst['errcode']!=0){
                //记录异常日志
                (new ErrorLogModel())->addLog($userId, "wexin_template", $rst);
            }
        }else{
            //记录异常日志
            (new ErrorLogModel())->addLog($userId, "wexin_template_id_empty", $weixinTemplateObj);
        }
        
    }
    
}
?>